package com.base.components.zuul.configuration;

import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.cloud.netflix.zuul.filters.discovery.DiscoveryClientRouteLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * ApiDocConfiguration
 *
 * @author <a href="drakelee1221@gmail.com">LiGeng</a>
 * @version 1.0.0, 2018-12-14 23:33
 */
@Configuration
@ConditionalOnProperty(name = "api-doc.swagger.gateway.enabled", havingValue = "true")
@SuppressWarnings("all")
public class ApiDocsGatewayConfiguration {
  @Autowired
  private DispatcherServletPath dispatcherServletPath;

  @Bean(value = "discoveryRouteLocator")
  public DiscoveryClientRouteLocator discoveryClientRouteLocator(ServerProperties server, DiscoveryClient discovery,
                                                                 ZuulProperties properties,
                                                                 ServiceInstance localInstance) {

    return new DiscoveryClientRouteLocator(
      dispatcherServletPath.getPrefix(), discovery, properties, localInstance) {
      /** api-docs-route 在 base.filters.authorization.authMap 设置不过滤权限 */
      private String routeId = "api-docs-route";
      private String docPath = "/v2/api-docs";
      private String groupParam = "group";
      @PostConstruct
      public void init() {
        addRoute(new ZuulProperties.ZuulRoute(routeId, docPath + "**", null, null, false, true, null));
      }
      @Override
      public Route getMatchingRoute(String path) {
        try {
          if (path.startsWith(docPath)) {
            String group = RequestContext.getCurrentContext().getRequest().getParameter(groupParam);
            if (StringUtils.isNotBlank(group)) {
              return new Route(routeId, path, group, null, false, null, false);
            }
          }
        } catch (Exception ignore) {
        }
        return super.getMatchingRoute(path);
      }
    };
  }
}
